package cn.quang.search.admin.service.impl;

import cn.quang.search.admin.entity.dto.Operator;
import cn.quang.search.admin.entity.dto.Result;
import cn.quang.search.admin.entity.po.*;
import cn.quang.search.admin.entity.vo.scene.SearchSceneMockParamVO;
import cn.quang.search.admin.entity.vo.scene.SearchSceneRequest;
import cn.quang.search.admin.enums.EntityTableFieldTypeEnum;
import cn.quang.search.admin.enums.PresetConditionValueTypeEnum;
import cn.quang.search.admin.enums.SearchSceneConfigTypeEnum;
import cn.quang.search.admin.mapper.*;
import cn.quang.search.admin.service.ISearchConfigChangeService;
import cn.quang.search.admin.service.ISearchSceneService;
import cn.quang.search.admin.service.common.RedisService;
import cn.quang.search.admin.utils.AssertUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: Entity Generator
 * @since: 2024-02-28 11:20:54
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SearchSceneService implements ISearchSceneService {
    private final SearchSceneMapper searchSceneMapper;
    private final SearchSceneConfigMapper searchSceneConfigMapper;
    private final SearchSceneFetcherConfigMapper searchSceneFetcherConfigMapper;
    private final SearchSceneInnerFetcherConfigMapper searchSceneInnerFetcherConfigMapper;
    private final SearchSceneInnerFetcherFieldConfigMapper searchSceneInnerFetcherFieldConfigMapper;
    private final SearchScenePresetConditionConfigMapper searchScenePresetConditionConfigMapper;
    private final SearchSceneContextConfigMapper searchSceneContextConfigMapper;
    private final SearchConditionTableRelationMapper searchConditionTableRelationMapper;
    private final SearchResultFetcherTableRelationMapper searchResultFetcherTableRelationMapper;
    private final EntityLogicTableMapper entityLogicTableMapper;
    private final EntityLogicTableFieldDicMapper entityLogicTableFieldDicMapper;
    private final SearchResultFetcherMapper searchResultFetcherMapper;
    private final EntityFieldDicMapper entityFieldDicMapper;
    private final SearchConditionMapper searchConditionMapper;
    private final SearchResultInnerFetcherMapper searchResultInnerFetcherMapper;
    private final SearchResultInnerFetcherFieldDicMapper searchResultInnerFetcherFieldDicMapper;

    private final ISearchConfigChangeService searchConfigChangeService;
    private final RedisService redisService;

    private static final String LOCK_KEY = "CRM3$SEARCH_SCENE$";
    private static final int EXPIRE_SECONDS = 60;

//    @Override
//    public Result<Pagination<SearchSceneListItemVO>> list4View(Operator operator, SearchSceneQueryRequest request) {
//        Result<Pagination<SearchSceneListItemVO>> aopResult = new Result<>();
//
//        SearchGroup searchGroup = new SearchGroup(SearchLogicType.AND);
//        if (StringUtils.isNotBlank(request.getCode())) {
//            searchGroup.addSearch(SearchScene.COL_CODE, SearchOperator.Equal, request.getCode());
//        }
//        if (StringUtils.isNotBlank(request.getName())) {
//            searchGroup.addSearch(SearchScene.COL_NAME, SearchOperator.Equal, request.getName());
//        }
//        if (StringUtils.isNotBlank(request.getStartCreateTime())) {
//            Date startCreateTime = DateUtil.parse(request.getStartCreateTime(), DateUtil.PATTERN_FULL);
//            searchGroup.addSearch(SearchScene.COL_CREATE_TIME, SearchOperator.GreaterThanOrEqual, startCreateTime);
//        }
//        if (StringUtils.isNotBlank(request.getEndCreateTime())) {
//            Date endCreateTime = DateUtil.parse(request.getEndCreateTime(), DateUtil.PATTERN_FULL);
//            searchGroup.addSearch(SearchScene.COL_CREATE_TIME, SearchOperator.LessThan, endCreateTime);
//        }
//        try {
//            Pagination<SearchScene> entitiesPagination = this.searchSceneMapper.findEntitiesPagination(null, searchGroup, request.getPageIndex(), request.getPageSize(), String.format("%s desc", EntityDataSource.COL_CREATE_TIME));
//            Pagination<SearchSceneListItemVO> pagination = new Pagination<>(request.getPageIndex(), request.getPageSize(), entitiesPagination.getTotalCount());
//            if (CollectionUtils.isNotEmpty(entitiesPagination)) {
//                for (SearchScene searchScene : entitiesPagination) {
//                    pagination.add(convertToListItemVo(searchScene));
//                }
//            }
//            return aopResult.changeSucc(pagination);
//        } catch (Exception e) {
//            logger.error("逻辑表查询失败", e);
//            return aopResult.changeErr("逻辑表查询失败：" + e.getMessage());
//        }
//    }

//    private SearchSceneListItemVO convertToListItemVo(SearchScene searchScene) {
//        SearchSceneListItemVO vo = new SearchSceneListItemVO();
//        vo.setId(searchScene.getId());
//        vo.setCode(searchScene.getCode());
//        vo.setName(searchScene.getName());
//        vo.setDescription(searchScene.getDescription());
//        vo.setCreatorName(BspService.getBspUserNameById(searchScene.getCreatorId()));
//        vo.setCreateTimeFormat(DateUtil.format(searchScene.getCreateTime()));
//        vo.setModifierName(BspService.getBspUserNameById(searchScene.getModifierId()));
//        vo.setModifyTimeFormat(DateUtil.format(searchScene.getModifyTime()));
//        return vo;
//    }

//    @Override
//    public Result<SearchSceneDetailVO> detail4View(Operator operator, long id) {
//        Result<SearchSceneDetailVO> aopResult = new Result<>();
//        try {
//            SearchScene entity = searchSceneMapper.findEntityById(id);
//            return aopResult.changeSucc(convertToDetailVo(entity));
//        } catch (Exception e) {
//            logger.error(String.format("逻辑表(%s)查询失败", id), e);
//            return aopResult.changeErr("逻辑表详情查询失败：" + e.getMessage());
//        }
//    }

//    private SearchSceneDetailVO convertToDetailVo(SearchScene entity) {
//        long sceneId = entity.getId();
//        SearchSceneDetailVO vo = new SearchSceneDetailVO();
//        vo.setId(sceneId);
//        vo.setCode(entity.getCode());
//        vo.setName(entity.getName());
//        vo.setDescription(entity.getDescription());
//        // 开始读取关联的逻辑
//        try {
//            List<SearchSceneConfig> configs = searchSceneConfigMapper.selectBySceneId(sceneId);
//            SearchSceneConfig tableConfig = Objects.requireNonNull(configs.stream().filter(input -> input.getConfigType() == SearchSceneConfigTypeEnum.LOGIC_TABLE.getCode()).findAny().orElse(null));
//            // 获取table
//            long logicTableId = tableConfig.getConfigId();
//            EntityLogicTable logicTable = entityLogicTableMapper.findEntityById(logicTableId);
//            LogicTableVO tableVO = new LogicTableVO();
//            tableVO.setLogicTableId(logicTableId);
//            tableVO.setLogicTableName(logicTable.getName());
//            vo.setLogicTable(tableVO);
//            // 预设查询条件
//            convertToPresetConditionDetailVo(sceneId, vo);
//            // 上下文
//            convertToContextDetailVo(sceneId, vo);
//            // 必须注册的查询条件
//            convertToConditionDetailVo(configs, logicTableId, vo);
//            // 取数器
//            convertToFetcherDetailVo(sceneId, logicTableId, vo);
//            // 取数字典
//            convertToFieldDicDetailVo(configs, logicTableId, vo);
//            // 内置取数器
//            convertToInnerFetcherDetailVo(sceneId, vo);
//        } catch (Exception e) {
//            logger.error("转换成场景视图详情出现异常", e);
//        }
//        return vo;
//    }

    /**
     * 处理详情视图中的预设查询条件
     *
     * @param sceneId  场景ID
     * @param detailVO 详情
     */
//    private void convertToPresetConditionDetailVo(long sceneId, SearchSceneDetailVO detailVO) throws Exception {
//        List<SearchPresetConditionVO> vos = Lists.newArrayList();
//        List<SearchScenePresetConditionConfig> searchScenePresetConditionConfigs = searchScenePresetConditionConfigMapper.selectBySceneId(sceneId);
//        if (CollectionUtils.isNotEmpty(searchScenePresetConditionConfigs)) {
//            for (SearchScenePresetConditionConfig searchScenePresetConditionConfig : searchScenePresetConditionConfigs) {
//                SearchPresetConditionVO vo = new SearchPresetConditionVO();
//                int fieldType = searchScenePresetConditionConfig.getFieldType();
//                vo.setFieldType(fieldType);
//                if(fieldType == 1) {
//                    vo.setIdForFieldDic(searchScenePresetConditionConfig.getFieldDicId());
//                }
//                if(fieldType == 2) {
//                    vo.setIdForConditionDic(searchScenePresetConditionConfig.getFieldDicId());
//                }
//                vo.setOperator(searchScenePresetConditionConfig.getOperator());
//                PresetConditionValueTypeEnum typeEnum = PresetConditionValueTypeEnum.getByCode(searchScenePresetConditionConfig.getType());
//                vo.setType(typeEnum.getCode());
//                if (typeEnum == PresetConditionValueTypeEnum.SYSTEM_VAR) {
//                    vo.setValueForVar(Integer.parseInt(searchScenePresetConditionConfig.getValue()));
//                }
//                if (typeEnum == PresetConditionValueTypeEnum.CONTEXT) {
//                    vo.setValueForContext(Long.parseLong(searchScenePresetConditionConfig.getValue()));
//                }
//                if (typeEnum == PresetConditionValueTypeEnum.INPUT) {
//                    vo.setValueForInput(searchScenePresetConditionConfig.getValue());
//                }
//                vos.add(vo);
//            }
//        }
//        detailVO.setPresetConditions(vos);
//    }

    /**
     * 处理详情视图中的上下文
     */
//    private void convertToContextDetailVo(long sceneId, SearchSceneDetailVO detailVO) throws Exception {
//        List<SearchContextVO> contexts = Lists.newArrayList();
//        List<SearchSceneContextConfig> searchSceneContextConfigs = searchSceneContextConfigMapper.selectBySceneId(sceneId);
//        if (CollectionUtils.isNotEmpty(searchSceneContextConfigs)) {
//            for (SearchSceneContextConfig searchSceneContextConfig : searchSceneContextConfigs) {
//                SearchContextVO vo = new SearchContextVO();
//                vo.setContextId(searchSceneContextConfig.getId());
//                vo.setContextName(String.format("%s(%s)", searchSceneContextConfig.getDic(), searchSceneContextConfig.getName()));
//                contexts.add(vo);
//            }
//        }
//        detailVO.setContexts(contexts);
//    }

    /**
     * 处理详情视图中的查询条件
     */
//    private void convertToConditionDetailVo(List<SearchSceneConfig> configs, long logicTableId, SearchSceneDetailVO vo) throws Exception {
//        // 获取查询条件
//        List<SearchSceneConfig> conditionConfigs = configs.stream().filter(input -> input.getConfigType() == SearchSceneConfigTypeEnum.CONDITION.getCode()).collect(Collectors.toList());
//        List<Long> conditionIds = conditionConfigs.stream().map(SearchSceneConfig::getConfigId).collect(Collectors.toList());
//        List<SearchCondition> conditions = searchConditionMapper.findEntitiesByIds(conditionIds);
//        List<SearchConditionVO> conditionVOs = conditions.stream().map(input -> {
//            SearchConditionVO conditionVO = new SearchConditionVO();
//            conditionVO.setConditionId(input.getId());
//            conditionVO.setConditionName(input.getName());
//            return conditionVO;
//        }).collect(Collectors.toList());
//        vo.setAlwaysRegisterConditions(conditionVOs);
//        // 为了兼容视图，需要同步返回视图关联逻辑表下的所有查询条件
//        List<SearchConditionTableRelation> conditionTableRelations = searchConditionTableRelationMapper.selectByLogicTableId(logicTableId);
//        List<SearchConditionListItemVO> vos = Lists.newArrayList();
//        if (CollectionUtils.isNotEmpty(conditionTableRelations)) {
//            List<Long> allConditionIds = conditionTableRelations.stream().map(SearchConditionTableRelation::getConditionId).collect(Collectors.toList());
//            List<SearchCondition> entitiesByIds = searchConditionMapper.findEntitiesByIds(allConditionIds);
//            if (CollectionUtils.isNotEmpty(entitiesByIds)) {
//                for (SearchCondition condition : entitiesByIds) {
//                    SearchConditionListItemVO listItemVO = new SearchConditionListItemVO();
//                    listItemVO.setId(condition.getId());
//                    listItemVO.setDic(condition.getDic());
//                    listItemVO.setName(condition.getName());
//                    listItemVO.setDescription(condition.getDescription());
//                    vos.add(listItemVO);
//                }
//            }
//        }
//        vo.setLogicTableConditions(vos);
//    }

    /**
     * 处理详情视图中的取数器
     */
//    private void convertToFetcherDetailVo(long sceneId, long logicTableId, SearchSceneDetailVO vo) throws Exception {
//        // 获取取数器
//        List<SearchSceneFetcherConfig> fetcherConfigs = searchSceneFetcherConfigMapper.selectBySceneId(sceneId);
//        Map<Long, SearchSceneFetcherConfig> fetcherConfigMap = fetcherConfigs.stream().collect(Collectors.toMap(SearchSceneFetcherConfig::getFetcherId, v -> v));
//        List<Long> fetcherIds = fetcherConfigs.stream().map(SearchSceneFetcherConfig::getFetcherId).collect(Collectors.toList());
//        List<SearchResultFetcher> fetchers = searchResultFetcherMapper.findEntitiesByIds(fetcherIds);
//        List<SearchResultFetcherVO> fetcherVOs = fetchers.stream().map(input -> {
//            SearchResultFetcherVO fetcherVO = new SearchResultFetcherVO();
//            fetcherVO.setResultFetcherId(input.getId());
//            fetcherVO.setResultFetcherName(input.getName());
//            SearchSceneFetcherConfig searchSceneFetcherConfig = fetcherConfigMap.get(input.getId());
//            fetcherVO.setSupportSort(searchSceneFetcherConfig.getSupportSort() == DBConstants.DATA_TRUE);
//            fetcherVO.setRecommendSortFieldDicId(searchSceneFetcherConfig.getRecommendSortFieldDicId());
//            return fetcherVO;
//        }).collect(Collectors.toList());
//        vo.setResultFetchers(fetcherVOs);
//        // 为了兼容视图，需要同步返回视图关联逻辑表下的所有取数器
//        List<SearchResultFetcherTableRelation> fetcherTableRelations = searchResultFetcherTableRelationMapper.selectByLogicTableId(logicTableId);
//        List<SearchResultFetcherListItemVO> vos = Lists.newArrayList();
//        if (CollectionUtils.isNotEmpty(fetcherTableRelations)) {
//            List<Long> allFetcherIds = fetcherTableRelations.stream().map(SearchResultFetcherTableRelation::getFetcherId).collect(Collectors.toList());
//            List<SearchResultFetcher> entitiesByIds = searchResultFetcherMapper.findEntitiesByIds(allFetcherIds);
//            if (CollectionUtils.isNotEmpty(entitiesByIds)) {
//                for (SearchResultFetcher fetcher : entitiesByIds) {
//                    SearchResultFetcherListItemVO listItemVO = new SearchResultFetcherListItemVO();
//                    listItemVO.setId(fetcher.getId());
//                    listItemVO.setDic(fetcher.getDic());
//                    listItemVO.setName(fetcher.getName());
//                    listItemVO.setDescription(fetcher.getDescription());
//                    vos.add(listItemVO);
//                }
//            }
//        }
//        vo.setLogicTableFetchers(vos);
//    }

    /**
     * 处理详情视图中的取数字典
     */
//    private void convertToFieldDicDetailVo(List<SearchSceneConfig> configs, long logicTableId, SearchSceneDetailVO vo) throws Exception {
//        // 获取通用字典
//        List<SearchSceneConfig> fieldDicConfigs = configs.stream().filter(input -> input.getConfigType() == SearchSceneConfigTypeEnum.FIELD_DIC.getCode()).collect(Collectors.toList());
//        List<Long> fieldDicIds = fieldDicConfigs.stream().map(SearchSceneConfig::getConfigId).collect(Collectors.toList());
//        List<EntityFieldDic> fieldDices = entityFieldDicMapper.findEntitiesByIds(fieldDicIds);
//        List<FieldDicVO> fieldDicVOs = fieldDices.stream().map(input -> {
//            FieldDicVO fieldDicVo = new FieldDicVO();
//            fieldDicVo.setFieldDicId(input.getId());
//            fieldDicVo.setFieldDicName(String.format("%s(%s)", input.getDic(), input.getName()));
//            return fieldDicVo;
//        }).collect(Collectors.toList());
//        vo.setFieldDices(fieldDicVOs);
//        // 为了兼容视图，需要同步返回视图关联逻辑表下的所有通用字典
//        List<FieldDicListItemVO> vos = Lists.newArrayList();
//        List<EntityLogicTableFieldDic> entityLogicTableFieldDices = entityLogicTableFieldDicMapper.selectByLogicTableId(logicTableId);
//        if (CollectionUtils.isNotEmpty(entityLogicTableFieldDices)) {
//            Map<Long, EntityLogicTableFieldDic> logicTableFieldDicMap = entityLogicTableFieldDices.stream().collect(Collectors.toMap(EntityLogicTableFieldDic::getFieldDicId, v -> v));
//            List<EntityFieldDic> allFieldDices = entityFieldDicMapper.findEntitiesByIds(Lists.newArrayList(logicTableFieldDicMap.keySet()));
//            if (CollectionUtils.isNotEmpty(allFieldDices)) {
//                for (EntityFieldDic fieldDic : allFieldDices) {
//                    FieldDicListItemVO fieldDicListItemVO = new FieldDicListItemVO();
//                    fieldDicListItemVO.setId(fieldDic.getId());
//                    fieldDicListItemVO.setName(fieldDic.getName());
//                    fieldDicListItemVO.setDic(fieldDic.getDic());
//                    fieldDicListItemVO.setDescription(fieldDic.getDescription());
//                    vos.add(fieldDicListItemVO);
//                }
//            }
//        }
//        vo.setLogicTableFieldDices(vos);
//    }

    /**
     * 处理详情视图中的内置取数器
     */
//    private void convertToInnerFetcherDetailVo(long sceneId, SearchSceneDetailVO vo) throws Exception {
//        // 获取内置取数器
//        List<SearchSceneInnerFetcherConfig> innerFetcherConfigs = searchSceneInnerFetcherConfigMapper.selectBySceneId(sceneId);
//        if (CollectionUtils.isNotEmpty(innerFetcherConfigs)) {
//            List<Long> innerFetcherIds = innerFetcherConfigs.stream().map(SearchSceneInnerFetcherConfig::getInnerFetcherId).collect(Collectors.toList());
//            List<SearchResultInnerFetcher> innerFetchers = searchResultInnerFetcherMapper.findEntitiesByIds(innerFetcherIds);
//			Map<Long, SearchResultInnerFetcher> innerFetcherMap = innerFetchers.stream().collect(Collectors.toMap(SearchResultInnerFetcher::getId, v -> v));
//            List<SearchSceneInnerFetcherVO> innerFetcherVOS = Lists.newArrayList();
//            // 读取innerFetcher，并读取innerFetcher下配置的字典
//            for (SearchSceneInnerFetcherConfig innerFetcherConfig : innerFetcherConfigs) {
//                SearchSceneInnerFetcherVO innerFetcherVO = new SearchSceneInnerFetcherVO();
//                innerFetcherVO.setInnerFetcherId(innerFetcherConfig.getInnerFetcherId());
//				SearchResultInnerFetcher searchResultInnerFetcher = innerFetcherMap.get(innerFetcherConfig.getInnerFetcherId());
//				innerFetcherVO.setInnerFetcherName(searchResultInnerFetcher.getName());
//                innerFetcherVO.setDic(innerFetcherConfig.getDic());
//                innerFetcherVO.setName(innerFetcherConfig.getName());
//                innerFetcherVO.setDescription(innerFetcherConfig.getDescription());
//                innerFetcherVO.setSupportSort(innerFetcherConfig.getSupportSort() == DBConstants.DATA_TRUE);
//                innerFetcherVO.setRecommendSortFieldDicId(innerFetcherConfig.getRecommendSortFieldDicId());
//                // 读取该内置取数器下配置的字段
//                List<SearchSceneInnerFetcherFieldConfig> innerFetcherFieldConfigs = searchSceneInnerFetcherFieldConfigMapper.selectByInnerFetcherConfigId(innerFetcherConfig.getId());
//                if (CollectionUtils.isNotEmpty(innerFetcherFieldConfigs)) {
//                    List<Long> fieldDicIds = innerFetcherFieldConfigs.stream().map(SearchSceneInnerFetcherFieldConfig::getFieldDicId).distinct().collect(Collectors.toList());
//                    List<EntityFieldDic> fieldDices = entityFieldDicMapper.findEntitiesByIds(fieldDicIds);
//                    Map<Long, EntityFieldDic> fieldDicMap = fieldDices.stream().collect(Collectors.toMap(EntityFieldDic::getId, v -> v));
//                    List<Long> innerFetcherFieldDicIds = innerFetcherFieldConfigs.stream().map(SearchSceneInnerFetcherFieldConfig::getInnerFetcherFieldDicId).distinct().collect(Collectors.toList());
//                    List<SearchResultInnerFetcherFieldDic> innerFetcherFieldDices = searchResultInnerFetcherFieldDicMapper.findEntitiesByIds(innerFetcherFieldDicIds);
//                    Map<Long, SearchResultInnerFetcherFieldDic> innerFetcherFieldDicMap = innerFetcherFieldDices.stream().collect(Collectors.toMap(SearchResultInnerFetcherFieldDic::getId, v -> v));
//                    List<SearchSceneInnerFetcherFieldDicVO> innerFetcherFieldDicVOS = Lists.newArrayList();
//                    for (SearchSceneInnerFetcherFieldConfig innerFetcherFieldConfig : innerFetcherFieldConfigs) {
//                        SearchSceneInnerFetcherFieldDicVO innerFetcherFieldDicVO = new SearchSceneInnerFetcherFieldDicVO();
//                        SearchResultInnerFetcherFieldDic innerFetcherFieldDic = innerFetcherFieldDicMap.get(innerFetcherFieldConfig.getInnerFetcherFieldDicId());
//                        innerFetcherFieldDicVO.setInnerFetcherFieldDicId(innerFetcherFieldDic.getId());
//                        innerFetcherFieldDicVO.setInnerFetcherFieldDicName(String.format("%s(%s)", innerFetcherFieldDic.getRequireFieldName(), innerFetcherFieldDic.getRequireFieldDescription()));
//                        EntityFieldDic fieldDic = fieldDicMap.get(innerFetcherFieldConfig.getFieldDicId());
//                        innerFetcherFieldDicVO.setFieldDicId(fieldDic.getId());
//                        innerFetcherFieldDicVO.setFieldDicName(String.format("%s(%s)", fieldDic.getDic(), fieldDic.getName()));
//                        innerFetcherFieldDicVOS.add(innerFetcherFieldDicVO);
//                    }
//                    innerFetcherVO.setInnerFetcherFieldDices(innerFetcherFieldDicVOS);
//                }
//                innerFetcherVOS.add(innerFetcherVO);
//            }
//            vo.setResultInnerFetchers(innerFetcherVOS);
//        }
//    }

    /**
     * 添加查询场景
     *
     * @param operator 操作人
     * @param request  场景添加请求
     */
    @Override
    public Result<Long> add(Operator operator, SearchSceneRequest request) {
        Result<Long> aopResult = new Result<>();
        AssertUtils.argumentBlank(request.getCode(), "必须提供场景标识");
        AssertUtils.argumentBlank(request.getName(), "必须提供场景名称");
        SearchSceneRequest.LogicTableRequest logicTable = request.getLogicTable();
        AssertUtils.argumentNull(logicTable, "必须提供场景关联的逻辑表");

        String sceneCode = request.getCode();
        String uniqueKey = LOCK_KEY + sceneCode;
        String requestId = UUID.randomUUID().toString();
        Result<?> checkResult = checkInputParams(request);
        if (checkResult.isFail()) {
            return aopResult.changeErr(checkResult.getMessage());
        }

        if (redisService.tryLock(uniqueKey, requestId, EXPIRE_SECONDS)) {
            try {
                SearchScene searchScene = searchSceneMapper.selectBySceneCode(sceneCode);
                if (searchScene != null) {
                    return aopResult.changeErr("系统已存在Code为" + sceneCode + "的场景");
                }
                // 校验结束，开始执行保存
                Date now = new Date();
                searchScene = new SearchScene();
                searchScene.setCode(request.getCode());
                searchScene.setName(request.getName());
                searchScene.setDescription(request.getDescription());
                searchScene.setCreatorId(operator.getOperatorId());
                searchScene.setCreateTime(now);
                searchScene.setModifierId(operator.getOperatorId());
                searchScene.setModifyTime(now);
                searchSceneMapper.insert(searchScene);
                Long sceneId = searchScene.getId();
                // 添加场景和表的对应关系
                SearchSceneConfig tableConfig = constructSceneConfig(operator, sceneId, SearchSceneConfigTypeEnum.LOGIC_TABLE, logicTable.getLogicTableId(), now);
                searchSceneConfigMapper.insert(tableConfig);
                List<SearchSceneRequest.SearchConditionRequest> searchConditions = request.getAlwaysRegisterConditions();
                if (CollectionUtils.isNotEmpty(searchConditions)) {
                    // 添加场景和查询条件的对应关系
                    for (SearchSceneRequest.SearchConditionRequest searchCondition : searchConditions) {
                        SearchSceneConfig conditionConfig = constructSceneConfig(operator, sceneId, SearchSceneConfigTypeEnum.CONDITION, searchCondition.getConditionId(), now);
                        searchSceneConfigMapper.insert(conditionConfig);
                    }
                }
                // 添加场景和预设查询条件的对应关系
                List<SearchSceneRequest.SearchPresetConditionRequest> presetConditions = request.getPresetConditions();
                if (CollectionUtils.isNotEmpty(presetConditions)) {
                    for (SearchSceneRequest.SearchPresetConditionRequest presetCondition : presetConditions) {
                        SearchScenePresetConditionConfig config = new SearchScenePresetConditionConfig();
                        config.setSceneId(sceneId);
                        int fieldType = presetCondition.getFieldType();
                        config.setFieldType(fieldType);
                        if(fieldType == 1) {
                            config.setFieldDicId(presetCondition.getIdForFieldDic());
                        } else if(fieldType == 2) {
                            config.setFieldDicId(presetCondition.getIdForConditionDic());
                        }
                        config.setOperator(presetCondition.getOperator());
                        config.setType(presetCondition.getType());
                        config.setValue(presetCondition.getValueForDb());
                        config.setCreatorId(operator.getOperatorId());
                        config.setCreateTime(now);
                        config.setModifierId(operator.getOperatorId());
                        config.setModifyTime(now);
                        searchScenePresetConditionConfigMapper.insert(config);
                    }
                }
                List<SearchSceneRequest.SearchResultFetcherRequest> requestResultFetchers = request.getResultFetchers();
                if (CollectionUtils.isNotEmpty(requestResultFetchers)) {
                    // 添加场景和取数器的对应关系
                    for (SearchSceneRequest.SearchResultFetcherRequest requestResultFetcher : requestResultFetchers) {
                        SearchSceneFetcherConfig searchSceneFetcherConfig = new SearchSceneFetcherConfig();
                        searchSceneFetcherConfig.setSceneId(sceneId);
                        searchSceneFetcherConfig.setFetcherId(requestResultFetcher.getResultFetcherId());
                        searchSceneFetcherConfig.setSupportSort(requestResultFetcher.isSupportSort());
                        searchSceneFetcherConfig.setRecommendSortFieldDicId(requestResultFetcher.getRecommendSortFieldDicId());
                        searchSceneFetcherConfig.setCreatorId(operator.getOperatorId());
                        searchSceneFetcherConfig.setCreateTime(now);
                        searchSceneFetcherConfig.setModifierId(operator.getOperatorId());
                        searchSceneFetcherConfig.setModifyTime(now);
                        searchSceneFetcherConfigMapper.insert(searchSceneFetcherConfig);
                    }
                }
                List<SearchSceneRequest.FieldDicRequest> requestFieldDices = request.getFieldDices();
                if (CollectionUtils.isNotEmpty(requestFieldDices)) {
                    // 添加场景和通用字典的对应关系
                    for (SearchSceneRequest.FieldDicRequest requestFieldDic : requestFieldDices) {
                        SearchSceneConfig fieldDicConfig = constructSceneConfig(operator, sceneId, SearchSceneConfigTypeEnum.FIELD_DIC, requestFieldDic.getFieldDicId(), now);
                        searchSceneConfigMapper.insert(fieldDicConfig);
                    }
                }
                // 新增内置取数器
                List<SearchSceneRequest.SearchResultInnerFetcherRequest> resultInnerFetchers = request.getResultInnerFetchers();
                if (CollectionUtils.isNotEmpty(resultInnerFetchers)) {
                    for (SearchSceneRequest.SearchResultInnerFetcherRequest resultInnerFetcher : resultInnerFetchers) {
                        SearchSceneInnerFetcherConfig innerFetcherConfig = new SearchSceneInnerFetcherConfig();
                        innerFetcherConfig.setInnerFetcherId(resultInnerFetcher.getInnerFetcherId());
                        innerFetcherConfig.setSceneId(sceneId);
                        innerFetcherConfig.setDic(resultInnerFetcher.getDic());
                        innerFetcherConfig.setName(resultInnerFetcher.getName());
                        innerFetcherConfig.setDescription(resultInnerFetcher.getDescription());
                        innerFetcherConfig.setSupportSort(resultInnerFetcher.isSupportSort());
                        innerFetcherConfig.setRecommendSortFieldDicId(resultInnerFetcher.getRecommendSortFieldDicId());
                        innerFetcherConfig.setCreatorId(operator.getOperatorId());
                        innerFetcherConfig.setCreateTime(now);
                        innerFetcherConfig.setModifierId(operator.getOperatorId());
                        innerFetcherConfig.setModifyTime(now);
                        searchSceneInnerFetcherConfigMapper.insert(innerFetcherConfig);
                        Long sceneInnerFetcherConfigId = innerFetcherConfig.getInnerFetcherId();
                                // 继续添加配置项绑定关系
                        List<SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest> innerFetcherFieldDices = resultInnerFetcher.getInnerFetcherFieldDices();
                        if (CollectionUtils.isNotEmpty(innerFetcherFieldDices)) {
                            for (SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest innerFetcherFieldDice : innerFetcherFieldDices) {
                                SearchSceneInnerFetcherFieldConfig sceneInnerFetcherFieldConfig = new SearchSceneInnerFetcherFieldConfig();
                                sceneInnerFetcherFieldConfig.setFieldDicId(innerFetcherFieldDice.getFieldDicId());
                                sceneInnerFetcherFieldConfig.setInnerFetcherFieldDicId(innerFetcherFieldDice.getInnerFetcherFieldDicId());
                                sceneInnerFetcherFieldConfig.setSceneInnerFetcherConfigId(sceneInnerFetcherConfigId);
                                sceneInnerFetcherFieldConfig.setCreateTime(now);
                                sceneInnerFetcherFieldConfig.setCreatorId(operator.getOperatorId());
                                sceneInnerFetcherFieldConfig.setModifyTime(now);
                                sceneInnerFetcherFieldConfig.setModifierId(operator.getOperatorId());
                                searchSceneInnerFetcherFieldConfigMapper.insert(sceneInnerFetcherFieldConfig);
                            }
                        }
                    }

                }
                searchConfigChangeService.triggerBySceneId(sceneId);
            } catch (Exception e) {
                log.error("添加场景失败", e);
                return aopResult.changeErr("场景添加失败，系统异常：" + e.getMessage());
            } finally {
                redisService.releaseLock(uniqueKey, requestId);
            }
        }

        return aopResult;
    }

    /**
     * 构造查询场景配置
     */
    private SearchSceneConfig constructSceneConfig(Operator operator, long sceneId, SearchSceneConfigTypeEnum type, long configId, Date now) {
        SearchSceneConfig conditionConfig = new SearchSceneConfig();
        conditionConfig.setConfigId(configId);
        conditionConfig.setSceneId(sceneId);
        conditionConfig.setConfigType(type.getCode());
        conditionConfig.setCreatorId(operator.getOperatorId());
        conditionConfig.setCreateTime(now);
        conditionConfig.setModifierId(operator.getOperatorId());
        conditionConfig.setModifyTime(now);
        return conditionConfig;
    }

    /**
     * 更新场景
     *
     * @param operator 操作人
     * @param sceneId  场景ID
     * @param request  请求
     */
    @Override
    public Result<?> update(Operator operator, long sceneId, SearchSceneRequest request) {
        Result<?> aopResult = new Result<>();

        SearchScene searchScene = searchSceneMapper.selectById(sceneId);
        AssertUtils.argumentNull(searchScene, "该场景不存在，无法更新！");

        Result<?> checkResult = checkInputParams(request);
        if (checkResult.isFail()) {
            return aopResult.changeErr(checkResult.getMessage());
        }

        String sceneCode = StringUtils.isBlank(request.getCode()) ? searchScene.getCode() : request.getCode();
        String uniqueKey  = LOCK_KEY + sceneCode;
        String requestId = UUID.randomUUID().toString();
        if (redisService.tryLock(uniqueKey, requestId, EXPIRE_SECONDS)) {
            try {
                if (!sceneCode.equals(searchScene.getCode())) {
                    SearchScene searchSceneByCode = searchSceneMapper.selectBySceneCode(sceneCode);
                    if (searchSceneByCode != null) {
                        return aopResult.changeErr("系统已存在Code为" + sceneCode + "的场景");
                    }
                }

                Date now = new Date();
                searchScene.setCode(sceneCode);
                searchScene.setName(request.getName());
                searchScene.setDescription(request.getDescription());
                searchScene.setModifierId(operator.getOperatorId());
                searchScene.setModifyTime(now);
                searchSceneMapper.updateById(searchScene);

                List<SearchSceneConfig> sceneConfigs = searchSceneConfigMapper.selectBySceneId(sceneId);
                updateSceneLogicTable(operator, sceneConfigs, request, now);
                updatePresetCondition(operator, sceneId, request, now);
                updateSceneAlwaysRegisterCondition(operator, sceneId, sceneConfigs, request, now);
                updateSearchResultFetcher(operator, sceneId, request, now);
                updateFieldDic(operator, sceneId, sceneConfigs, request, now);
                updateSearchResultInnerFetcher(operator, sceneId, request, now);

                searchConfigChangeService.triggerBySceneId(sceneId);
            } catch (Exception e) {
                log.error(String.format("查询场景(%s)变更失败", sceneId), e);
                return aopResult.changeErr("查询场景更新失败: " + e.getMessage());
            } finally {
                redisService.releaseLock(uniqueKey, requestId);
            }
        }
        return aopResult;
    }

    /**
     * 更新逻辑表
     *
     * @param operator     操作人
     * @param sceneConfigs 场景关联配置
     * @param request      请求
     * @param now          当前时间
     */
    private void updateSceneLogicTable(Operator operator, List<SearchSceneConfig> sceneConfigs, SearchSceneRequest request, Date now) throws Exception {
        // 更新逻辑表
        SearchSceneRequest.LogicTableRequest requestLogicTable = request.getLogicTable();
        SearchSceneConfig logicTableConfig = sceneConfigs.stream().filter(config -> config.getConfigType() == SearchSceneConfigTypeEnum.LOGIC_TABLE.getCode()).findAny().orElse(null);
        if (logicTableConfig == null) {
            throw new IllegalStateException("未检索到该场景对应的逻辑表，更新已终止");
        }
        logicTableConfig.setConfigId(requestLogicTable.getLogicTableId());
        logicTableConfig.setModifierId(operator.getOperatorId());
        logicTableConfig.setModifyTime(now);
        searchSceneConfigMapper.updateById(logicTableConfig);
    }

    /**
     * 更新预设查询条件
     *
     * @param operator 操作人
     * @param request  请求
     * @param now      当前时间
     */
    private void updatePresetCondition(Operator operator, long sceneId, SearchSceneRequest request, Date now) throws Exception {

        class Key {
            private String getKey(int fieldType, long fieldDicId, String operator) {
                return String.format("%s_%s(%s)", fieldType, fieldDicId, operator);
            }
        }
        Key key = new Key();
        // 存储增删改的条件名称，用于输出日志
        List<SearchSceneRequest.SearchPresetConditionRequest> presetConditionRequests = request.getPresetConditions();
        List<String> newPresetConditions = Lists.newArrayList();
        List<String> modifyPresetConditions = Lists.newArrayList();
        List<String> deletePresetConditions = Lists.newArrayList();
        // 比较更新逻辑表关系 ： 存在的更新，不存在的新增，未出现在请求中的删除
        List<SearchScenePresetConditionConfig> presetConditions = searchScenePresetConditionConfigMapper.selectBySceneId(sceneId);
        Map<String, SearchScenePresetConditionConfig> presetConditionConfigMap = presetConditions.stream().collect(Collectors.toMap(k -> key.getKey(k.getFieldType(), k.getFieldDicId(), k.getOperator()), v -> v));
        for (SearchSceneRequest.SearchPresetConditionRequest presetConditionRequest : presetConditionRequests) {
            long requestFieldDicId = presetConditionRequest.getFieldType() == 1 ? presetConditionRequest.getIdForFieldDic() : presetConditionRequest.getIdForConditionDic();
            SearchScenePresetConditionConfig config = presetConditionConfigMap.get(key.getKey(presetConditionRequest.getFieldType(), requestFieldDicId, presetConditionRequest.getOperator()));
            if (config != null) {
                // 已存在的关联关系，执行更新
                config.setType(presetConditionRequest.getType());
                config.setValue(presetConditionRequest.getValueForDb());
                config.setModifierId(operator.getOperatorId());
                config.setModifyTime(now);
                searchScenePresetConditionConfigMapper.updateById(config);
                modifyPresetConditions.add(String.format("%s(%s)", presetConditionRequest.getFieldDicName(), presetConditionRequest.getOperator()));
            } else {
                // 新增
                config = new SearchScenePresetConditionConfig();
                config.setSceneId(sceneId);
                int fieldType = presetConditionRequest.getFieldType();
                config.setFieldType(fieldType);
                if(fieldType == 1) {
                    config.setFieldDicId(presetConditionRequest.getIdForFieldDic());
                } else if(fieldType == 2) {
                    config.setFieldDicId(presetConditionRequest.getIdForConditionDic());
                }
                config.setOperator(presetConditionRequest.getOperator());
                config.setType(presetConditionRequest.getType());
                config.setValue(presetConditionRequest.getValueForDb());
                config.setCreatorId(operator.getOperatorId());
                config.setCreateTime(now);
                config.setModifierId(operator.getOperatorId());
                config.setModifyTime(now);
                searchScenePresetConditionConfigMapper.insert(config);
                newPresetConditions.add(String.format("%s(%s)", presetConditionRequest.getFieldDicName(), presetConditionRequest.getOperator()));
            }
        }
        Map<String, SearchSceneRequest.SearchPresetConditionRequest> requestConditionMap = presetConditionRequests.stream().collect(Collectors.toMap(k -> key.getKey(k.getFieldType(), k.getFieldType() == 1 ? k.getIdForFieldDic() : k.getIdForConditionDic(), k.getOperator()), v -> v));
        // 执行删除
        for (SearchScenePresetConditionConfig config : presetConditions) {
            if (!requestConditionMap.containsKey(key.getKey(config.getFieldType(), config.getFieldDicId(), config.getOperator()))) {
                String fieldName;
                if(config.getFieldType() == 1) {
                    EntityFieldDic fieldDic = entityFieldDicMapper.selectById(config.getFieldDicId());
                    fieldName = fieldDic == null ? "未知" : String.format("%s(%s)", fieldDic.getDic(), fieldDic.getName());
                } else {
                    SearchCondition condition = searchConditionMapper.selectById(config.getFieldDicId());
                    fieldName = condition == null ? "未知" : String.format("%s(%s)", condition.getDic(), condition.getName());
                }
                String valueTypeName = PresetConditionValueTypeEnum.getNameByCode(config.getType());
                // 删除
                searchScenePresetConditionConfigMapper.deleteById(config.getId());
                deletePresetConditions.add(String.format("%s(%s)", fieldName, valueTypeName));
            }
        }
        log.info(String.format("场景关联预设条件：新增条件%s，修改条件%s，删除条件%s", newPresetConditions, modifyPresetConditions, deletePresetConditions));
    }

    /**
     * 更新场景注册的查询条件
     *
     * @param operator     操作人
     * @param sceneId      场景ID
     * @param sceneConfigs 场景关联配置
     * @param request      请求
     * @param now          当前时间
     */
    private void updateSceneAlwaysRegisterCondition(Operator operator, long sceneId, List<SearchSceneConfig> sceneConfigs, SearchSceneRequest request, Date now) throws Exception {
        // 存储增删改的条件名称，用于输出日志
        List<SearchSceneRequest.SearchConditionRequest> requestSearchConditions = request.getAlwaysRegisterConditions();
        List<String> newConditionNames = Lists.newArrayList();
        List<String> modifyConditionNames = Lists.newArrayList();
        List<String> deleteConditionNames = Lists.newArrayList();
        // 比较更新逻辑表关系 ： 存在的更新，不存在的新增，未出现在请求中的删除
        List<SearchSceneConfig> conditionRelations = sceneConfigs.stream().filter(config -> config.getConfigType() == SearchSceneConfigTypeEnum.CONDITION.getCode()).collect(Collectors.toList());
        Map<Long, SearchSceneConfig> conditionConfigMap = conditionRelations.stream().collect(Collectors.toMap(SearchSceneConfig::getConfigId, v -> v));
        for (SearchSceneRequest.SearchConditionRequest searchConditionRequest : requestSearchConditions) {
            SearchSceneConfig relation = conditionConfigMap.get(searchConditionRequest.getConditionId());
            if (relation != null) {
                // 已存在的关联关系，执行更新
                relation.setModifierId(operator.getOperatorId());
                relation.setModifyTime(now);
                searchSceneConfigMapper.updateById(relation);
                modifyConditionNames.add(searchConditionRequest.getConditionName());
            } else {
                // 新增
                relation = constructSceneConfig(operator, sceneId, SearchSceneConfigTypeEnum.CONDITION, searchConditionRequest.getConditionId(), now);
                searchSceneConfigMapper.insert(relation);
                newConditionNames.add(searchConditionRequest.getConditionName());
            }
        }
        Map<Long, SearchSceneRequest.SearchConditionRequest> requestConditionMap = requestSearchConditions.stream().collect(Collectors.toMap(SearchSceneRequest.SearchConditionRequest::getConditionId, v -> v));
        // 执行删除
        for (SearchSceneConfig relation : conditionRelations) {
            if (!requestConditionMap.containsKey(relation.getConfigId())) {
                SearchCondition condition = searchConditionMapper.selectById(relation.getConfigId());
                // 删除
                searchSceneConfigMapper.deleteById(relation.getId());
                deleteConditionNames.add(condition == null ? "未知" : condition.getName());
            }
        }
        log.info(String.format("场景关联查询条件：新增条件%s，修改条件%s，删除条件%s", newConditionNames, modifyConditionNames, deleteConditionNames));
    }

    /**
     * 更新场景注册的取数器
     *
     * @param operator     操作人
     * @param sceneId      场景ID
     * @param request      请求
     * @param now          当前时间
     */
    private void updateSearchResultFetcher(Operator operator, long sceneId, SearchSceneRequest request, Date now) throws Exception {
        // 存储增删改的取数器名称，用于输出日志
        List<SearchSceneRequest.SearchResultFetcherRequest> requestResultFetchers = request.getResultFetchers();
        List<String> newFetcherNames = Lists.newArrayList();
        List<String> modifyFetcherNames = Lists.newArrayList();
        List<String> deleteFetcherNames = Lists.newArrayList();
        // 比较更新逻辑表关系 ： 存在的更新，不存在的新增，未出现在请求中的删除
        List<SearchSceneFetcherConfig> fetcherConfigs = searchSceneFetcherConfigMapper.selectBySceneId(sceneId);
        Map<Long, SearchSceneFetcherConfig> fetcherConfigMap = fetcherConfigs.stream().collect(Collectors.toMap(SearchSceneFetcherConfig::getFetcherId, v -> v));
        for (SearchSceneRequest.SearchResultFetcherRequest searchFetcherRequest : requestResultFetchers) {
            SearchSceneFetcherConfig searchSceneFetcherConfig = fetcherConfigMap.get(searchFetcherRequest.getResultFetcherId());
            if (searchSceneFetcherConfig != null) {
                // 已存在的关联关系，执行更新
                searchSceneFetcherConfig.setSupportSort(searchFetcherRequest.isSupportSort());
                searchSceneFetcherConfig.setRecommendSortFieldDicId(searchFetcherRequest.getRecommendSortFieldDicId());
                searchSceneFetcherConfig.setModifierId(operator.getOperatorId());
                searchSceneFetcherConfig.setModifyTime(now);
                searchSceneFetcherConfigMapper.updateById(searchSceneFetcherConfig);
                modifyFetcherNames.add(searchFetcherRequest.getResultFetcherName());
            } else {
                // 新增
                searchSceneFetcherConfig = new SearchSceneFetcherConfig();
                searchSceneFetcherConfig.setSceneId(sceneId);
                searchSceneFetcherConfig.setFetcherId(searchFetcherRequest.getResultFetcherId());
                searchSceneFetcherConfig.setSupportSort(searchFetcherRequest.isSupportSort());
                searchSceneFetcherConfig.setRecommendSortFieldDicId(searchFetcherRequest.getRecommendSortFieldDicId());
                searchSceneFetcherConfig.setCreatorId(operator.getOperatorId());
                searchSceneFetcherConfig.setCreateTime(now);
                searchSceneFetcherConfig.setModifierId(operator.getOperatorId());
                searchSceneFetcherConfig.setModifyTime(now);
                searchSceneFetcherConfigMapper.insert(searchSceneFetcherConfig);
                newFetcherNames.add(searchFetcherRequest.getResultFetcherName());
            }
        }
        Map<Long, SearchSceneRequest.SearchResultFetcherRequest> requestFetcherMap = requestResultFetchers.stream().collect(Collectors.toMap(SearchSceneRequest.SearchResultFetcherRequest::getResultFetcherId, v -> v));
        // 执行删除
        for (SearchSceneFetcherConfig searchSceneFetcherConfig : fetcherConfigs) {
            if (!requestFetcherMap.containsKey(searchSceneFetcherConfig.getFetcherId())) {
                SearchResultFetcher fetcher = searchResultFetcherMapper.selectById(searchSceneFetcherConfig.getFetcherId());
                // 删除
                searchSceneFetcherConfigMapper.deleteById(searchSceneFetcherConfig.getId());
                deleteFetcherNames.add(fetcher == null ? "未知" : fetcher.getName());
            }
        }
        log.info(String.format("场景关联查询取数器：新增取数器%s，修改取数器%s，删除取数器%s", newFetcherNames, modifyFetcherNames, deleteFetcherNames));
    }

    /**
     * 更新场景注册的取数字典
     *
     * @param operator     操作人
     * @param sceneId      场景ID
     * @param sceneConfigs 场景关联配置
     * @param request      请求
     * @param now          当前时间
     */
    private void updateFieldDic(Operator operator, long sceneId, List<SearchSceneConfig> sceneConfigs, SearchSceneRequest request, Date now) throws Exception {
        // 更新fieldDic
        // 存储增删改的取数器名称，用于输出日志
        List<SearchSceneRequest.FieldDicRequest> requestFieldDices = request.getFieldDices();
        List<String> newFieldDicNames = Lists.newArrayList();
        List<String> modifyFieldDicNames = Lists.newArrayList();
        List<String> deleteFieldDicNames = Lists.newArrayList();
        // 比较更新逻辑表关系 ： 存在的更新，不存在的新增，未出现在请求中的删除
        List<SearchSceneConfig> fieldDicRelation = sceneConfigs.stream().filter(config -> config.getConfigType() == SearchSceneConfigTypeEnum.FIELD_DIC.getCode()).collect(Collectors.toList());
        Map<Long, SearchSceneConfig> fieldDicConfigMap = fieldDicRelation.stream().collect(Collectors.toMap(SearchSceneConfig::getConfigId, v -> v));
        for (SearchSceneRequest.FieldDicRequest fieldDicRequest : requestFieldDices) {
            SearchSceneConfig relation = fieldDicConfigMap.get(fieldDicRequest.getFieldDicId());
            if (relation != null) {
                // 已存在的关联关系，执行更新
                relation.setModifierId(operator.getOperatorId());
                relation.setModifyTime(now);
                searchSceneConfigMapper.updateById(relation);
                modifyFieldDicNames.add(fieldDicRequest.getFieldDicName());
            } else {
                // 新增
                relation = constructSceneConfig(operator, sceneId, SearchSceneConfigTypeEnum.FIELD_DIC, fieldDicRequest.getFieldDicId(), now);
                searchSceneConfigMapper.insert(relation);
                newFieldDicNames.add(fieldDicRequest.getFieldDicName());
            }
        }
        Map<Long, SearchSceneRequest.FieldDicRequest> requestFieldDicMap = requestFieldDices.stream().collect(Collectors.toMap(SearchSceneRequest.FieldDicRequest::getFieldDicId, v -> v));
        // 执行删除
        for (SearchSceneConfig relation : fieldDicRelation) {
            if (!requestFieldDicMap.containsKey(relation.getConfigId())) {
                EntityFieldDic fieldDic = entityFieldDicMapper.selectById(relation.getConfigId());
                // 删除
                searchSceneConfigMapper.deleteById(relation.getId());
                deleteFieldDicNames.add(fieldDic == null ? "未知" : fieldDic.getName());
            }
        }
        log.info(String.format("场景关联通用字典：新增通用字典%s，修改通用字典%s，删除通用字典%s", newFieldDicNames, modifyFieldDicNames, deleteFieldDicNames));
    }

    /**
     * 更新场景注册的内置取数器
     *
     * @param operator 操作人
     * @param sceneId  场景ID
     * @param request  请求
     * @param now      当前时间
     */
    private void updateSearchResultInnerFetcher(Operator operator, long sceneId, SearchSceneRequest request, Date now) throws Exception {

		class Key {
			String getKey(long innerFetcherId, String dic) {
				return String.format("KEY_%s_%s", innerFetcherId, dic);
			}
		}
		Key key = new Key();
        // 存储增删改的取数器名称，用于输出日志
        List<SearchSceneRequest.SearchResultInnerFetcherRequest> innerFetcherRequests = request.getResultInnerFetchers();
        List<String> newInnerFetchers = Lists.newArrayList();
        List<String> modifyInnerFetchers = Lists.newArrayList();
        List<String> deleteInnerFetchers = Lists.newArrayList();
        // 比较更新逻辑表关系 ： 存在的更新，不存在的新增，未出现在请求中的删除
        List<SearchSceneInnerFetcherConfig> innerFetcherConfigs = searchSceneInnerFetcherConfigMapper.selectBySceneId(sceneId);

        Map<String, SearchSceneRequest.SearchResultInnerFetcherRequest> requestInnerFetcherMap = innerFetcherRequests.stream().collect(Collectors.toMap(k -> key.getKey(k.getInnerFetcherId(), k.getDic()), v -> v));
        // 先执行删除
        for (SearchSceneInnerFetcherConfig config : innerFetcherConfigs) {
            String uniqueKey = key.getKey(config.getInnerFetcherId(), config.getDic());
            if (!requestInnerFetcherMap.containsKey(uniqueKey)) {
                SearchResultInnerFetcher innerFetcher = searchResultInnerFetcherMapper.selectById(config.getInnerFetcherId());
                // 删除关联的取数字典
                List<SearchSceneInnerFetcherFieldConfig> innerFetcherFieldConfigs = searchSceneInnerFetcherFieldConfigMapper.selectByInnerFetcherConfigId(config.getId());
                if (CollectionUtils.isNotEmpty(innerFetcherFieldConfigs)) {
                    for (SearchSceneInnerFetcherFieldConfig innerFetcherFieldConfig : innerFetcherFieldConfigs) {
                        searchSceneInnerFetcherFieldConfigMapper.deleteById(innerFetcherFieldConfig.getId());
                    }
                }
                // 删除场景和内置取数器的关联
                searchSceneInnerFetcherConfigMapper.deleteById(config.getId());
                deleteInnerFetchers.add(innerFetcher == null ? "未知" : innerFetcher.getName());
            }
        }

        Map<String, SearchSceneInnerFetcherConfig> fieldDicConfigMap = innerFetcherConfigs.stream().collect(Collectors.toMap(k -> key.getKey(k.getInnerFetcherId(), k.getDic()), v -> v));
        for (SearchSceneRequest.SearchResultInnerFetcherRequest innerFetcherRequest : innerFetcherRequests) {
			String uniqueKey = key.getKey(innerFetcherRequest.getInnerFetcherId(), innerFetcherRequest.getDic());
            SearchSceneInnerFetcherConfig sceneInnerFetcherConfig = fieldDicConfigMap.get(uniqueKey);
            if (sceneInnerFetcherConfig != null) {
                // 已存在的关联关系，执行更新
                sceneInnerFetcherConfig.setName(innerFetcherRequest.getName());
                sceneInnerFetcherConfig.setDescription(innerFetcherRequest.getDescription());
                sceneInnerFetcherConfig.setSupportSort(innerFetcherRequest.isSupportSort());
                sceneInnerFetcherConfig.setRecommendSortFieldDicId(innerFetcherRequest.getRecommendSortFieldDicId());
                sceneInnerFetcherConfig.setModifierId(operator.getOperatorId());
                sceneInnerFetcherConfig.setModifyTime(now);
                searchSceneInnerFetcherConfigMapper.updateById(sceneInnerFetcherConfig);
                // 更新fieldDic
                List<SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest> innerFetcherFieldDicRequests = innerFetcherRequest.getInnerFetcherFieldDices();
                List<String> newFieldDices = Lists.newArrayList();
                List<String> modifyFieldDices = Lists.newArrayList();
                List<String> deleteFieldDices = Lists.newArrayList();
                // 比较更新逻辑表关系 ： 存在的更新，不存在的新增，未出现在请求中的删除
                List<SearchSceneInnerFetcherFieldConfig> innerFetcherFieldConfigs = searchSceneInnerFetcherFieldConfigMapper.selectByInnerFetcherConfigId(sceneInnerFetcherConfig.getId());
                Map<Long, SearchSceneInnerFetcherFieldConfig> innerFetcherFieldConfigMap = innerFetcherFieldConfigs.stream().collect(Collectors.toMap(SearchSceneInnerFetcherFieldConfig::getInnerFetcherFieldDicId, v -> v));
                for (SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest innerFetcherFieldDicRequest : innerFetcherFieldDicRequests) {
                    SearchSceneInnerFetcherFieldConfig innerFetcherFieldConfig = innerFetcherFieldConfigMap.get(innerFetcherFieldDicRequest.getInnerFetcherFieldDicId());
                    if (innerFetcherFieldConfig != null) {
                        // 执行更新
                        innerFetcherFieldConfig.setFieldDicId(innerFetcherFieldDicRequest.getFieldDicId());
                        innerFetcherFieldConfig.setModifierId(operator.getOperatorId());
                        innerFetcherFieldConfig.setModifyTime(now);
                        searchSceneInnerFetcherFieldConfigMapper.updateById(innerFetcherFieldConfig);
                        modifyFieldDices.add(innerFetcherFieldDicRequest.getInnerFetcherFieldDicName());
                    } else {
                        // 新增
                        innerFetcherFieldConfig = new SearchSceneInnerFetcherFieldConfig();
                        innerFetcherFieldConfig.setSceneInnerFetcherConfigId(sceneInnerFetcherConfig.getId());
                        innerFetcherFieldConfig.setInnerFetcherFieldDicId(innerFetcherFieldDicRequest.getInnerFetcherFieldDicId());
                        innerFetcherFieldConfig.setFieldDicId(innerFetcherFieldDicRequest.getFieldDicId());
                        innerFetcherFieldConfig.setCreatorId(operator.getOperatorId());
                        innerFetcherFieldConfig.setCreateTime(now);
                        innerFetcherFieldConfig.setModifierId(operator.getOperatorId());
                        innerFetcherFieldConfig.setModifyTime(now);
                        searchSceneInnerFetcherFieldConfigMapper.insert(innerFetcherFieldConfig);
                        newFieldDices.add(innerFetcherFieldDicRequest.getInnerFetcherFieldDicName());
                    }
                }
                Map<Long, SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest> requestFieldDicMap = innerFetcherFieldDicRequests.stream().collect(Collectors.toMap(SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest::getInnerFetcherFieldDicId, v -> v));
                // 执行删除
                for (SearchSceneInnerFetcherFieldConfig relation : innerFetcherFieldConfigs) {
                    if (!requestFieldDicMap.containsKey(relation.getInnerFetcherFieldDicId())) {
                        SearchResultInnerFetcherFieldDic fieldDic = searchResultInnerFetcherFieldDicMapper.selectById(relation.getInnerFetcherFieldDicId());
                        // 删除
                        searchSceneInnerFetcherFieldConfigMapper.deleteById(relation.getId());
                        deleteFieldDices.add(fieldDic == null ? "未知" : fieldDic.getRequireFieldName());
                    }
                }
                log.info(String.format("场景关联内置取数器(%s)更新，该内置取数器关联的取数字典也一并更新：新增内置取数器关联字典%s，修改内置取数器关联字典%s，删除内置取数器关联字典%s", innerFetcherRequest.getInnerFetcherName(), newFieldDices, modifyFieldDices, deleteFieldDices));
                modifyInnerFetchers.add(innerFetcherRequest.getInnerFetcherName());
            } else {
                // 新增
                sceneInnerFetcherConfig = new SearchSceneInnerFetcherConfig();
                sceneInnerFetcherConfig.setName(innerFetcherRequest.getName());
                sceneInnerFetcherConfig.setDic(innerFetcherRequest.getDic());
                sceneInnerFetcherConfig.setDescription(innerFetcherRequest.getDescription());
                sceneInnerFetcherConfig.setInnerFetcherId(innerFetcherRequest.getInnerFetcherId());
                sceneInnerFetcherConfig.setSceneId(sceneId);
                sceneInnerFetcherConfig.setSupportSort(innerFetcherRequest.isSupportSort());
                sceneInnerFetcherConfig.setRecommendSortFieldDicId(innerFetcherRequest.getRecommendSortFieldDicId());
                sceneInnerFetcherConfig.setCreatorId(operator.getOperatorId());
                sceneInnerFetcherConfig.setCreateTime(now);
                sceneInnerFetcherConfig.setModifierId(operator.getOperatorId());
                sceneInnerFetcherConfig.setModifyTime(now);
                searchSceneInnerFetcherConfigMapper.insert(sceneInnerFetcherConfig);
                Long sceneInnerFetcherConfigId = sceneInnerFetcherConfig.getId();
                        // 同时新增字典关系
                List<SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest> innerFetcherFieldDices = innerFetcherRequest.getInnerFetcherFieldDices();
                if (CollectionUtils.isNotEmpty(innerFetcherFieldDices)) {
                    for (SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest innerFetcherFieldDicRequest : innerFetcherFieldDices) {
                        SearchSceneInnerFetcherFieldConfig fieldConfig = new SearchSceneInnerFetcherFieldConfig();
                        fieldConfig.setSceneInnerFetcherConfigId(sceneInnerFetcherConfigId);
                        fieldConfig.setInnerFetcherFieldDicId(innerFetcherFieldDicRequest.getInnerFetcherFieldDicId());
                        fieldConfig.setFieldDicId(innerFetcherFieldDicRequest.getFieldDicId());
                        fieldConfig.setCreatorId(operator.getOperatorId());
                        fieldConfig.setCreateTime(now);
                        fieldConfig.setModifierId(operator.getOperatorId());
                        fieldConfig.setModifyTime(now);
                        searchSceneInnerFetcherFieldConfigMapper.insert(fieldConfig);
                    }
                }
                newInnerFetchers.add(innerFetcherRequest.getInnerFetcherName());
            }
        }
        log.info(String.format("场景关联内置取数器：新增内置取数器%s，修改内置取数器%s，删除内置取数器%s", newInnerFetchers, modifyInnerFetchers, deleteInnerFetchers));
    }

    /**
     * 核验本次入参
     *
     * @param request 请求
     */
    private Result<?> checkInputParams(SearchSceneRequest request) {
        Result<?> aopResult = new Result<>();
        SearchSceneRequest.LogicTableRequest logicTable = request.getLogicTable();
        // 校验预设查询条件
        List<SearchSceneRequest.SearchPresetConditionRequest> presetConditions = request.getPresetConditions();
        if (CollectionUtils.isNotEmpty(presetConditions)) {
            for (SearchSceneRequest.SearchPresetConditionRequest presetCondition : presetConditions) {
                int type = presetCondition.getType();
                if (type == PresetConditionValueTypeEnum.SYSTEM_VAR.getCode()) {
                    int var = presetCondition.getValueForVar();
                    if (var <= 0) {
                        return aopResult.changeErr("预设系统变量条件必须提供依赖的系统变量");
                    }
                    presetCondition.setValueForDb(String.valueOf(var));
                }
                if (type == PresetConditionValueTypeEnum.CONTEXT.getCode()) {
                    long context = presetCondition.getValueForContext();
                    if (context <= 0) {
                        return aopResult.changeErr("预设上下文查询条件必须提供上下文变量Key");
                    }
                    presetCondition.setValueForDb(String.valueOf(context));
                }
                if (type == PresetConditionValueTypeEnum.INPUT.getCode()) {
                    String valueForInput = presetCondition.getValueForInput();
                    if (StringUtils.isBlank(valueForInput)) {
                        return aopResult.changeErr("预设操作符条件必须提供值");
                    }
                    presetCondition.setValueForDb(valueForInput);
                }
                if (StringUtils.isBlank(presetCondition.getValueForDb())) {
                    return aopResult.changeErr("必须选择预设查询条件的操作值");
                }
            }
        } else {
            presetConditions = Lists.newArrayList();
            request.setPresetConditions(presetConditions);
        }
        // 查询条件校验
        List<SearchSceneRequest.SearchConditionRequest> searchConditions = request.getAlwaysRegisterConditions();
        if (CollectionUtils.isNotEmpty(searchConditions)) {
            for (SearchSceneRequest.SearchConditionRequest searchCondition : searchConditions) {
                // 检查查询条件和视图表对应的逻辑表ID是否一致
                List<SearchConditionTableRelation> tableRelations = searchConditionTableRelationMapper.selectByConditionId(searchCondition.getConditionId());
                if (CollectionUtils.isEmpty(tableRelations) || tableRelations.stream().noneMatch(relation -> relation.getLogicTableId() == logicTable.getLogicTableId())) {
                    return aopResult.changeErr(String.format("您选择的条件（%s）并未归属逻辑表（%s），无法关联至场景", searchCondition.getConditionName(), logicTable.getLogicTableName()));
                }
            }
        } else {
            searchConditions = Lists.newArrayList();
            request.setAlwaysRegisterConditions(searchConditions);
        }

        List<EntityLogicTableFieldDic> logicTableFieldDices = entityLogicTableFieldDicMapper.selectByLogicTableId(logicTable.getLogicTableId());

        // 取数器和通用字典校验
        List<SearchSceneRequest.SearchResultFetcherRequest> requestResultFetchers = request.getResultFetchers();
        List<SearchSceneRequest.FieldDicRequest> requestFieldDices = request.getFieldDices();
        List<SearchSceneRequest.SearchResultInnerFetcherRequest> resultInnerFetchers = request.getResultInnerFetchers();
        if (CollectionUtils.isEmpty(requestResultFetchers) && CollectionUtils.isEmpty(requestFieldDices) && CollectionUtils.isEmpty(resultInnerFetchers)) {
            return aopResult.changeErr("取数器、取数字典、内置取数器请至少选择一个。");
        }

        if (CollectionUtils.isNotEmpty(requestResultFetchers)) {
            for (SearchSceneRequest.SearchResultFetcherRequest resultFetcher : requestResultFetchers) {
                List<SearchResultFetcherTableRelation> tableRelations = searchResultFetcherTableRelationMapper.selectByFetcherId(resultFetcher.getResultFetcherId());
                if (CollectionUtils.isEmpty(tableRelations) || tableRelations.stream().noneMatch(relation -> relation.getLogicTableId() == logicTable.getLogicTableId())) {
                    return aopResult.changeErr(String.format("您选择的取数器（%s）并未归属逻辑表（%s），无法关联至场景", resultFetcher.getResultFetcherName(), logicTable.getLogicTableName()));
                }
                boolean supportSort = resultFetcher.isSupportSort();
                if(supportSort) {
                    long recommendSortFieldDicId = resultFetcher.getRecommendSortFieldDicId();
                    if(recommendSortFieldDicId <= 0) {
                        return aopResult.changeErr(String.format("您选择的取数器（%s）已设置为支持排序，但未提供推荐排序字段", resultFetcher.getResultFetcherName()));
                    }
                    EntityLogicTableFieldDic logicTableFieldDic = logicTableFieldDices.stream().filter(input -> input.getFieldDicId() == recommendSortFieldDicId).findAny().orElse(null);
                    if(logicTableFieldDic == null) {
                        return aopResult.changeErr(String.format("您选择的取数器（%s）关联的推荐排序字段并不是逻辑表上关联的字段", resultFetcher.getResultFetcherName()));
                    }
                    if(logicTableFieldDic.getSupportQuery()) {
                        return aopResult.changeErr(String.format("您选择的取数器（%s）关联的推荐排序字段不支持排序，请仔细检查", resultFetcher.getResultFetcherName()));
                    }
                }
            }
        } else {
            requestResultFetchers = Lists.newArrayList();
            request.setResultFetchers(requestResultFetchers);
        }

        if (CollectionUtils.isNotEmpty(requestFieldDices)) {
            if (CollectionUtils.isEmpty(logicTableFieldDices)) {
                return aopResult.changeErr("选择的通用字典均未关联至选择的逻辑表的自定义字典中");
            }
            Map<Long, EntityLogicTableFieldDic> fieldDicMap = logicTableFieldDices.stream().collect(Collectors.toMap(EntityLogicTableFieldDic::getFieldDicId, v -> v));
            for (SearchSceneRequest.FieldDicRequest fieldDic : requestFieldDices) {
                if (!fieldDicMap.containsKey(fieldDic.getFieldDicId())) {
                    return aopResult.changeErr(String.format("您选择的通用字典（%s）并未关联至逻辑表（%s），无法关联至场景", fieldDic.getFieldDicName(), logicTable.getLogicTableName()));
                }
            }
        } else {
            requestFieldDices = Lists.newArrayList();
            request.setFieldDices(requestFieldDices);
        }

        // 内置取数器，必须提供Dic和对应的取数字典
        if (CollectionUtils.isNotEmpty(resultInnerFetchers)) {
            for (SearchSceneRequest.SearchResultInnerFetcherRequest resultInnerFetcher : resultInnerFetchers) {
                long innerFetcherId = resultInnerFetcher.getInnerFetcherId();
                if (innerFetcherId <= 0) {
                    return aopResult.changeErr("您选择了配置内置取数器，但未选择使用哪个内置取数器");
                }
                if (StringUtils.isBlank(resultInnerFetcher.getDic())) {
                    return aopResult.changeErr("每个内置取数器均需要提供Dic");
                }
                if (StringUtils.isBlank(resultInnerFetcher.getName())) {
                    return aopResult.changeErr("每个内置取数器均需要提供名称");
                }
                boolean supportSort = resultInnerFetcher.isSupportSort();
                if(supportSort) {
                    long recommendSortFieldDicId = resultInnerFetcher.getRecommendSortFieldDicId();
                    if(recommendSortFieldDicId <= 0) {
                        return aopResult.changeErr(String.format("您选择的内置取数器（%s）已设置为支持排序，但未提供推荐排序字段", resultInnerFetcher.getDic()));
                    }
                    EntityLogicTableFieldDic logicTableFieldDic = logicTableFieldDices.stream().filter(input -> input.getFieldDicId() == recommendSortFieldDicId).findAny().orElse(null);
                    if(logicTableFieldDic == null) {
                        return aopResult.changeErr(String.format("您选择的内置取数器（%s）关联的推荐排序字段并不是逻辑表上关联的字段", resultInnerFetcher.getDic()));
                    }
                    if(logicTableFieldDic.getSupportQuery()) {
                        return aopResult.changeErr(String.format("您选择的内置取数器（%s）关联的推荐排序字段不支持排序，请仔细检查", resultInnerFetcher.getDic()));
                    }
                }
                List<SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest> innerFetcherFieldDices = resultInnerFetcher.getInnerFetcherFieldDices();
                if (CollectionUtils.isNotEmpty(innerFetcherFieldDices)) {
                    for (SearchSceneRequest.SearchResultInnerFetcherFieldDicRequest innerFetcherFieldDic : innerFetcherFieldDices) {
                        if (innerFetcherFieldDic.getFieldDicId() <= 0) {
                            return aopResult.changeErr(String.format("内置取数器(%s)字段(%s)未关联取数字典", resultInnerFetcher.getDic(), innerFetcherFieldDic.getFieldDicName()));
                        }
                    }
                }
            }
        } else {
            resultInnerFetchers = Lists.newArrayList();
            request.setResultInnerFetchers(resultInnerFetchers);
        }

        // 不能选择重复的resultFetcher
        Set<Long> resultFetcherIds = Sets.newHashSet();
        for (SearchSceneRequest.SearchResultFetcherRequest resultFetcherRequest : requestResultFetchers) {
            if(resultFetcherIds.contains(resultFetcherRequest.getResultFetcherId())) {
                return aopResult.changeErr("自定义取数器(" + resultFetcherRequest.getResultFetcherName() + ")重复，请检查");
            }
            resultFetcherIds.add(resultFetcherRequest.getResultFetcherId());
        }
        // 重复Key校验
        List<Long> fieldDicIds = requestFieldDices.stream().map(SearchSceneRequest.FieldDicRequest::getFieldDicId).collect(Collectors.toList());
        List<SearchResultFetcher> fetchers = searchResultFetcherMapper.selectList(new QueryWrapper<SearchResultFetcher>().lambda().in(SearchResultFetcher::getId, Lists.newArrayList(resultFetcherIds)));
        List<EntityFieldDic> fieldDices = entityFieldDicMapper.selectList(new QueryWrapper<EntityFieldDic>().lambda().in(EntityFieldDic::getId, fieldDicIds));
        Set<String> fetcherKeys = fetchers.stream().map(SearchResultFetcher::getDic).collect(Collectors.toSet());
        Set<String> fieldKeys = fieldDices.stream().map(EntityFieldDic::getDic).collect(Collectors.toSet());
        ;
        Set<String> innerFetcherKeys = resultInnerFetchers.stream().map(SearchSceneRequest.SearchResultInnerFetcherRequest::getDic).collect(Collectors.toSet());

        Set<String> dupKeys = Sets.newHashSet();
        for (String fetcherKey : fetcherKeys) {
            if (!dupKeys.contains(fetcherKey)) {
                dupKeys.add(fetcherKey);
            } else {
                return aopResult.changeErr("取数器存在重复Dic：" + fetcherKey);
            }
        }
        for (String fieldKey : fieldKeys) {
            if (!dupKeys.contains(fieldKey)) {
                dupKeys.add(fieldKey);
            } else {
                return aopResult.changeErr("取数器、取数字典存在重复Dic：" + fieldKey);
            }
        }
        for (String innerFetcherKey : innerFetcherKeys) {
            if (!dupKeys.contains(innerFetcherKey)) {
                dupKeys.add(innerFetcherKey);
            } else {
                return aopResult.changeErr("取数器、取数字典和内置取数器存在重复Dic：" + innerFetcherKey);
            }
        }

        return aopResult;
    }

    /**
     * 删除场景
     *
     * @param operator 操作人
     * @param sceneId  场景ID
     */
    @Override
    public Result<?> delete(Operator operator, long sceneId) {
        Result<?> aopResult = new Result<>();
        try {
            SearchScene searchScene = searchSceneMapper.selectById(sceneId);
            if (searchScene == null) {
                return aopResult.changeErr("系统内不存在该查询场景");
            }

            // 删除场景关联的配置
            List<SearchSceneConfig> searchSceneConfigs = searchSceneConfigMapper.selectBySceneId(sceneId);
            if (CollectionUtils.isNotEmpty(searchSceneConfigs)) {
                for (SearchSceneConfig searchSceneConfig : searchSceneConfigs) {
                    searchSceneConfigMapper.deleteById(searchSceneConfig.getId());
                }
            }

            // 删除场景关联的取数器
            List<SearchSceneFetcherConfig> searchSceneFetcherConfigs = searchSceneFetcherConfigMapper.selectBySceneId(sceneId);
            if(CollectionUtils.isNotEmpty(searchSceneFetcherConfigs)) {
                for (SearchSceneFetcherConfig searchSceneFetcherConfig : searchSceneFetcherConfigs) {
                    searchSceneFetcherConfigMapper.deleteById(searchSceneFetcherConfig.getId());
                }
            }

            // 删除场景关联的上下文配置
            List<SearchSceneContextConfig> searchSceneContextConfigs = searchSceneContextConfigMapper.selectBySceneId(sceneId);
            if (CollectionUtils.isNotEmpty(searchSceneContextConfigs)) {
                for (SearchSceneContextConfig searchSceneContextConfig : searchSceneContextConfigs) {
                    searchSceneContextConfigMapper.deleteById(searchSceneContextConfig.getId());
                }
            }

            // 删除场景关联的预设查询条件配置
            List<SearchScenePresetConditionConfig> searchScenePresetConditionConfigs = searchScenePresetConditionConfigMapper.selectBySceneId(sceneId);
            if (CollectionUtils.isNotEmpty(searchScenePresetConditionConfigs)) {
                for (SearchScenePresetConditionConfig searchScenePresetConditionConfig : searchScenePresetConditionConfigs) {
                    searchScenePresetConditionConfigMapper.deleteById(searchScenePresetConditionConfig.getId());
                }
            }

            // 删除场景关联的内置取数器配置
            List<SearchSceneInnerFetcherConfig> sceneInnerFetcherConfigs = searchSceneInnerFetcherConfigMapper.selectBySceneId(sceneId);
            if (CollectionUtils.isNotEmpty(sceneInnerFetcherConfigs)) {
                for (SearchSceneInnerFetcherConfig sceneInnerFetcherConfig : sceneInnerFetcherConfigs) {
                    List<SearchSceneInnerFetcherFieldConfig> innerFetcherFieldConfigs = searchSceneInnerFetcherFieldConfigMapper.selectByInnerFetcherConfigId(sceneInnerFetcherConfig.getId());
                    if (CollectionUtils.isNotEmpty(innerFetcherFieldConfigs)) {
                        for (SearchSceneInnerFetcherFieldConfig innerFetcherFieldConfig : innerFetcherFieldConfigs) {
                            searchSceneInnerFetcherFieldConfigMapper.deleteById(innerFetcherFieldConfig.getId());
                        }
                    }
                    searchSceneInnerFetcherConfigMapper.deleteById(sceneInnerFetcherConfig.getId());
                }
            }
            searchSceneMapper.deleteById(sceneId);
        } catch (Exception e) {
            log.error(String.format("删除查询条件(%s)出现异常", sceneId), e);
            return aopResult.changeErr("删除查询条件出现系统异常：" + e.getMessage());
        }
        return aopResult;
    }

    @Override
    public Result<SearchSceneMockParamVO> mockQueryParam(Operator operator, long id) {
        Result<SearchSceneMockParamVO> aopResult = new Result<>();
        try {
            SearchSceneMockParamVO vo = new SearchSceneMockParamVO();

            List<SearchSceneMockParamVO.ConditionVO> conditions = Lists.newArrayList();
            List<SearchSceneConfig> searchSceneConfigs = searchSceneConfigMapper.selectBySceneId(id);
            SearchSceneConfig tableConfig = searchSceneConfigs.stream().filter(input -> input.getConfigType() == SearchSceneConfigTypeEnum.LOGIC_TABLE.getCode()).findAny().orElse(null);
            if(tableConfig == null) {
                return aopResult.changeErr("该场景未关联逻辑表！");
            }
            List<SearchConditionTableRelation> conditionTableRelations = searchConditionTableRelationMapper.selectByLogicTableId(tableConfig.getConfigId());
            if(CollectionUtils.isNotEmpty(conditionTableRelations)) {
                List<Long> conditionIds = conditionTableRelations.stream().map(SearchConditionTableRelation::getConditionId).distinct().collect(Collectors.toList());
                List<SearchCondition> conditionList = searchConditionMapper.selectList(new QueryWrapper<SearchCondition>().lambda().in(SearchCondition::getId, conditionIds));
                for (SearchCondition searchCondition : conditionList) {
                    SearchSceneMockParamVO.ConditionVO condition = new SearchSceneMockParamVO.ConditionVO();
                    condition.setConditionDic(searchCondition.getDic());
                    condition.setConditionName(String.format("%s(%s)", searchCondition.getDic(), searchCondition.getName()));
                    condition.setConditionValue(StringUtils.EMPTY);
                    conditions.add(condition);
                }
            }
            vo.setConditions(conditions);

            List<SearchSceneMockParamVO.FieldDicVO> commonConditions = Lists.newArrayList();
            List<EntityLogicTableFieldDic> entityLogicTableFieldDices = entityLogicTableFieldDicMapper.selectByLogicTableId(tableConfig.getConfigId());
            if(CollectionUtils.isNotEmpty(entityLogicTableFieldDices)) {
                List<Long> fieldDicIds = entityLogicTableFieldDices.stream().map(EntityLogicTableFieldDic::getFieldDicId).collect(Collectors.toList());
                List<EntityFieldDic> fieldDices = entityFieldDicMapper.selectList(new QueryWrapper<EntityFieldDic>().lambda().in(EntityFieldDic::getId, fieldDicIds));
                Map<Long, EntityLogicTableFieldDic> logicTableFieldDicMap = entityLogicTableFieldDices.stream().collect(Collectors.toMap(EntityLogicTableFieldDic::getFieldDicId, v -> v, (a, b) -> b));
                for (EntityFieldDic fieldDic : fieldDices) {
                    EntityLogicTableFieldDic logicTableFieldDic = logicTableFieldDicMap.get(fieldDic.getId());
                    if(logicTableFieldDic.getSupportQuery()) {
                        continue;
                    }
                    SearchSceneMockParamVO.FieldDicVO fieldDicVO = new SearchSceneMockParamVO.FieldDicVO();
                    fieldDicVO.setFieldDic(fieldDic.getDic());
                    fieldDicVO.setFieldName(String.format("%s(%s)", fieldDic.getDic(), fieldDic.getName()));
                    int queryFieldType = logicTableFieldDic.getQueryFieldType();
                    int resultFieldType = logicTableFieldDic.getResultFieldType();
                    if(resultFieldType == EntityTableFieldTypeEnum.Nested.getCode()) {
                        fieldDicVO.setSupportSuffix(true);
                        fieldDicVO.setSuffixes(Lists.newArrayList("-nestedKey", "-nestedValueStart", "-nestedValueStartEqual", "-nestedValueEnd", "nestedValueEndEqual"));
                    } else if(queryFieldType == EntityTableFieldTypeEnum.BigDecimal.getCode()
                            || queryFieldType == EntityTableFieldTypeEnum.Integer.getCode()
                            || queryFieldType == EntityTableFieldTypeEnum.Float.getCode()
                            || queryFieldType == EntityTableFieldTypeEnum.Double.getCode()
                            || queryFieldType == EntityTableFieldTypeEnum.Long.getCode()
                            || queryFieldType == EntityTableFieldTypeEnum.Short.getCode()) {
                        fieldDicVO.setSupportSuffix(true);
                        fieldDicVO.setSuffixes(Lists.newArrayList("-start", "-startEqual", "-end", "-endEqual"));
                    } else if(queryFieldType == EntityTableFieldTypeEnum.Date.getCode()) {
                        fieldDicVO.setSupportSuffix(true);
                        fieldDicVO.setSuffixes(Lists.newArrayList("-start", "-startEqual", "-end", "-endEqual", "recentDays", "recentWeeks", "recentMonths", "recentYears"));
                    } else {
                        fieldDicVO.setSupportSuffix(false);
                        fieldDicVO.setSuffixes(Lists.newArrayList());
                    }
                    commonConditions.add(fieldDicVO);
                }
            }
            vo.setCommonConditions(commonConditions);

            // 获取所有通用取数字典
            List<SearchSceneMockParamVO.FieldDicVO> fieldDices = Lists.newArrayList();
            List<SearchSceneConfig> fieldDicConfigs = searchSceneConfigs.stream().filter(input -> input.getConfigType() == SearchSceneConfigTypeEnum.FIELD_DIC.getCode()).collect(Collectors.toList());
            List<Long> fieldDicIds = fieldDicConfigs.stream().map(SearchSceneConfig::getConfigId).distinct().collect(Collectors.toList());
            List<EntityFieldDic> fieldDicList = entityFieldDicMapper.selectList(new QueryWrapper<EntityFieldDic>().lambda().in(EntityFieldDic::getId, fieldDicIds));
            for (EntityFieldDic entityFieldDic : fieldDicList) {
                SearchSceneMockParamVO.FieldDicVO fieldDicVO = new SearchSceneMockParamVO.FieldDicVO();
                fieldDicVO.setFieldDic(entityFieldDic.getDic());
                fieldDicVO.setFieldName(String.format("%s(%s)", entityFieldDic.getDic(), entityFieldDic.getName()));
                fieldDices.add(fieldDicVO);
            }
            vo.setFieldDices(fieldDices);

            // 获取所有内置取数器
            List<SearchSceneInnerFetcherConfig> sceneInnerFetcherConfigs = searchSceneInnerFetcherConfigMapper.selectBySceneId(id);
            List<SearchSceneMockParamVO.InnerFetcherVO> innerFetchers = Lists.newArrayList();
            if(CollectionUtils.isNotEmpty(sceneInnerFetcherConfigs)) {
                for (SearchSceneInnerFetcherConfig sceneInnerFetcherConfig : sceneInnerFetcherConfigs) {
                    SearchSceneMockParamVO.InnerFetcherVO innerFetcherVO = new SearchSceneMockParamVO.InnerFetcherVO();
                    innerFetcherVO.setInnerFetcherDic(sceneInnerFetcherConfig.getDic());
                    innerFetcherVO.setInnerFetcherName(String.format("%s(%s)", sceneInnerFetcherConfig.getDic(), sceneInnerFetcherConfig.getName()));
                    innerFetchers.add(innerFetcherVO);
                }
            }
            vo.setInnerFetchers(innerFetchers);
            // 获取所有自定义取数器
            List<SearchSceneFetcherConfig> searchSceneFetcherConfigs = searchSceneFetcherConfigMapper.selectBySceneId(id);
            List<SearchSceneMockParamVO.FetcherVO> fetchers = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(searchSceneFetcherConfigs)) {
                List<Long> fetcherIds = searchSceneFetcherConfigs.stream().map(SearchSceneFetcherConfig::getFetcherId).distinct().collect(Collectors.toList());
                List<SearchResultFetcher> fetcherList = searchResultFetcherMapper.selectList(new QueryWrapper<SearchResultFetcher>().lambda().in(SearchResultFetcher::getId, fetcherIds));
                for (SearchResultFetcher resultFetcher : fetcherList) {
                    SearchSceneMockParamVO.FetcherVO fetcherVO = new SearchSceneMockParamVO.FetcherVO();
                    fetcherVO.setFetcherDic(resultFetcher.getDic());
                    fetcherVO.setFetcherName(String.format("%s(%s)", resultFetcher.getDic(), resultFetcher.getName()));
                    fetchers.add(fetcherVO);
                }
            }
            vo.setFetchers(fetchers);

            return aopResult.changeSucc(vo);
        } catch (Exception e) {
            log.error(String.format("获取场景(ID=%s)的查询参数失败", id), e);
            return aopResult.changeErr("获取模拟查询参数失败");
        }
    }
}
